<script lang="ts" setup>
	import { onLaunch } from '@dcloudio/uni-app';
	import Bluetooth from './utils/Bluetooth';
	import { useBluetoothStore } from '@/store';

	/**
	 * 当蓝牙适配器的可用性和搜索状态发生变化时
	 */
	uni.$on('BluetoothAdapterAvailable', (available) => {
		if (!available) {
			jumpBluetoothSetting();
		}
	})
	/**
	 * 当与低功耗蓝牙设备的连接状态发生改变时
	 */
	uni.$on("BluetoothConnectState", (connected) => {
		if (!connected) {
			jumpBluetoothSetting();
		}
	})
	/**
	 * 蓝牙设备连接失败，有可能是超时
	 */
	uni.$on("BluetoothConnectionFail", (hasHistoryDevice) => {
		console.log("蓝牙设备连接失败，有可能是超时")
		if (!hasHistoryDevice) {
			jumpBluetoothSetting();
		}

	})

	onLaunch(async () => {
		checkLogin();
	})
	/**
	 * 检查登录，未登录则跳转
	 */
	const checkLogin = async () => {
		const token = uni.getStorageSync('token');
		if (!token) {
			uni.redirectTo({
				url: '/pages/login/index'
			})
		} else {
			connectBluetooth();
		}
	}

	const connectBluetooth = async () => {
		const bluetoothInstance = await Bluetooth.getInstance();
		const historyBluetoothDevice = uni.getStorageSync('historyBluetoothDevice');
		if (historyBluetoothDevice) {
			try {
				await bluetoothInstance.connectDevice(historyBluetoothDevice, true)
				return
			} catch (err) {
				console.error("历史连接失败")
			}
		}
		try {
			bluetoothInstance.startBluetoothDevicesDiscovery();
		} catch (err) {
			console.log('搜索蓝牙失败')
			jumpBluetoothSetting();
		}
	}


	const jumpBluetoothSetting = () => {
		const bluetoothStore = useBluetoothStore();
		if (bluetoothStore.isBlueSetting) return
		bluetoothStore.updatePageCurrent(true);
		uni.navigateTo({
			url: '/pages/bluetooth-setting/index'
		})
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	page {
		background-color: $uni-bg-color;
		font-family: PingFangSC, PingFang SC;
		color: $uni-text-color;
	}

	.no_data {
		width: 500rpx;
		height: 352rpx;
		padding: 0 125rpx;
		padding-top: 224rpx;
	}

	.no_data_title {
		width: 750rpx;
		height: 28rpx;
		font-size: 28rpx;
		color: #8A8A8A;
		line-height: 28rpx;
		text-align: center;
		user-select: none;
	}
</style>